package com.hmall.getway.fliter;

import cn.hutool.core.util.StrUtil;
import com.hmall.getway.config.AuthProperties;
import com.hmall.getway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class GlobalGatway implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final JwtTool jwtTool;

    /**
     * 鉴权
     *
     * @param exchange 请求与响应
     * @param chain    过滤链
     * @return 返回过滤链
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        List<String> excludePaths = authProperties.getExcludePaths();
        //白名单
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                return chain.filter(exchange);
            }
        }
        ServerHttpResponse response = exchange.getResponse();

        String token = request.getHeaders().getFirst("Authorization");
        //token为空
        if (StrUtil.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Long userId;
        //token鉴别
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
            request.mutate().header("user-info",userId.toString());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

